package com.springboot.auth.authorization.oauth2.enhancer;

import com.springboot.auth.authorization.model.vo.Authcode;
import com.springboot.auth.authorization.service.ISlidingCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by ZengJian on 2021/2/25 0025 下午 5:59
 */
public class QrTokenGranter extends ResourceOwnerPasswordTokenGranter {
    private static final String GRANT_TYPE = "officialaccount";

    private final AuthenticationManager authenticationManager;

    public QrTokenGranter(AuthenticationManager authenticationManager,
                          AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                          OAuth2RequestFactory requestFactory) {
        super(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String openId = parameters.get("openId");
        String sceneStr = parameters.get("sceneStr");
//            String captchaVerification=parameters.get("sceneStr");
//
//            System.out.println("captchaVerification:"+captchaVerification);

        Authentication userAuth = new UsernamePasswordAuthenticationToken(openId, sceneStr);
        QrAuthenticationToken qrAuthenticationToken = new QrAuthenticationToken(userAuth);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {

            userAuth = this.authenticationManager.authenticate(qrAuthenticationToken);

        } catch (AccountStatusException ase) {

            throw new InvalidGrantException(ase.getMessage());
        } catch (BadCredentialsException e) {

            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: " + openId);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, qrAuthenticationToken);
    }
}

